package com.synjones.wschool.face.feign;

import com.synjones.wschool.common.response.ResultBean;
import com.synjones.wschool.face.config.FeignMultipartSupportConfig;
import feign.hystrix.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文件存储相关 feign 接口
 *
 * @author zhuchangbin
 * @date 2017/10/31
 */
@FeignClient(name = "file-service", fallbackFactory = FileOperationService.FileOperationServiceFallBackFactory.class,
            configuration = FeignMultipartSupportConfig.class)
public interface FileOperationService {

    /**
     * 上传文件
     *
     * @param file 文件 file
     * @return ResultBean - String 返回文件地址
     */
    @PostMapping(value = "/file/local/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    ResultBean<String> uploadFile(@RequestPart("file") MultipartFile file);

    /**
     * 删除文件
     *
     * @param filePath 文件地址
     * @return ResultBean
     */
    @PostMapping(value = "/file/local/delete")
    ResultBean deleteFile(@RequestParam("filePath") String filePath);

    /***
     * 批量删除
     * @param filePathList
     * @return
     */
    @PostMapping(value = "/file/local/delete/batch")
    ResultBean batchDelFile(@RequestBody List<String> filePathList);


    /**
     * 下载文件
     *
     * @param filePath 文件地址
     * @return ResultBean byte[]
     */
    @PostMapping(value = "/file/local/download")
    ResultBean<byte[]> downloadFile(@RequestParam("filePath") String filePath);

    @Component
    class FileOperationServiceFallBackFactory implements FallbackFactory<FileOperationService> {

        private static final String SERVICE_NAME = "文件服务";

        @Override
        public FileOperationService create(Throwable throwable) {
            return new FileOperationService() {
                @Override
                public ResultBean<String> uploadFile(MultipartFile file) {
                    return ResultBean.fail(SERVICE_NAME + ":上传文件失败");
                }

                @Override
                public ResultBean deleteFile(String filePath) {
                    return ResultBean.fail(SERVICE_NAME + ":删除文件失败");
                }

                @Override
                public ResultBean<byte[]> downloadFile(String filePath) {
                    return ResultBean.fail(SERVICE_NAME + ":下载文件失败");
                }

                @Override
                public ResultBean batchDelFile(List<String> filePathList) {
                    return ResultBean.fail(SERVICE_NAME + ":批量删除文件失败");
                }
            };
        }
    }
}
